package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.client.DictFeignClient;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private DictFeignClient dictFeignClient;

    //上传医院信息
    @Override
    public void save(Map<String, Object> paramMap) {
        //1.封装参数数据
        //把map转换成json字符串
        String hospJsonStr = JSONObject.toJSONString(paramMap);
        //把json字符串转化为对象
        Hospital hospital = JSONObject.parseObject(hospJsonStr, Hospital.class);
        //2.判断医院信息是否存在
        Hospital targetHospital =
            hospitalRepository.getByHoscode(hospital.getHoscode());
        if (targetHospital != null){
            //3.mongo里有此医院信息做更新操作
            hospital.setId(targetHospital.getId());
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);

            hospitalRepository.save(hospital);
        }else {
            //mongo里没有此医院信息做新增操作
            //0:未上线 1：已上线
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }


    }
    //获取医院信息

    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.getByHoscode(hoscode);
    }
    //带查询条件、分页查询医院信息列表
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //1.创建分页对象

        //1.1创建排序对象
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
        //1.2创建分页对象 0为第一页
        Pageable pageable = PageRequest.of(page-1,limit,sort);
        //2.创建查询条件模板
        //2.1转换查询条件对象
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        //2.2创建匹配器
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        //2.3创建模板实例
        Example<Hospital> example = Example.of(hospital, matcher);

        //3.带条件带分页查询
        Page<Hospital> hospitalPage = hospitalRepository.findAll(example, pageable);

        //4.跨模块（cmn）调用查询字典 翻译编码信息
        hospitalPage.getContent().stream().forEach(item->{
            this.packHospital(item);
        });
        return hospitalPage;
    }
    //更新上线状态
    @Override
    public void updateStatus(String id, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }
    //获取医院详情
    @Override
    public Map<String, Object> getHospInfoById(String id) {
        Map<String, Object> result = new HashMap<>();
        //根据id查询，翻译补全信息
        Hospital hospital =
                this.packHospital(hospitalRepository.findById(id).get());
        //医院基本信息（包含医院等级）
        result.put("hospital",hospital);
        //单独处理更直观
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    @Override
    public String getHospName(String hoscode) {
        String hosname = "";
        Hospital hospital = this.getByHoscode(hoscode);
        if (hospital != null){
            hosname = hospital.getHosname();
        }

        return hosname;
    }
    //根据医院名称获取医院列表
    @Override
    public List<Hospital> findByHosname(String hosname) {
        List<Hospital> list = hospitalRepository.getByHosnameLike(hosname);
        return list;
    }
    //医院预约挂号详情
    @Override
    public Map<String, Object> getHospByHoscode(String hoscode) {
        Map<String,Object> result = new HashMap<>();
        //医院详情
        Hospital hospital = this.packHospital(hospitalRepository.getByHoscode(hoscode));
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    private Hospital packHospital(Hospital hospital) {
        String provinceCode = hospital.getProvinceCode();
        String provinceString = dictFeignClient.getName(provinceCode);
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());
        String hostypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(),hospital.getHostype());

        hospital.getParam().put("hostypeString", hostypeString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;
    }


}
